package 行为型模式


/**
 * 定义对象间的一种一对多的依赖关系，当一个对象的状态发生改变时，所有依赖于它的对象都得到通知并被自动更新
 */
class Store {
    private val observers: MutableList<ProductObserver> = ArrayList()
    private val products = HashMap<String, Product2>()

    // 注册观察者:
    fun addObserver(observer: ProductObserver) {
        observers.add(observer)
    }

    // 取消注册:
    fun removeObserver(observer: ProductObserver) {
        observers.remove(observer)
    }


    fun addNewProduct(name: String, price: Double) {
        val p = Product2(name, price)
        products[p.getName()] = p
        observers.forEach {
            it.onPublished(p)
        }
    }

    fun setProductPrice(name: String, price: Double) {
        val p = products[name]
        p?.setPrice(price)
        observers.forEach {
            it.onPriceChanged(p)
        }
    }

}

interface ProductObserver {
    fun onPublished(p: Product2) {

    }

    fun onPriceChanged(p: Product2?) {

    }

}

class Product2(private val name: String, private var price: Double) {
    @JvmName("getName1")
    fun getName(): String {
        return name
    }

    @JvmName("setPrice1")
    fun setPrice(price: Double) {
        this.price = price
    }

}

class Admin {

}

class Customer {

}

fun main2() {
    //匿名内部类
    Store().addObserver(object : ProductObserver {
        override fun onPriceChanged(p: Product2?) {
            super.onPriceChanged(p)
        }

        override fun onPublished(p: Product2) {
            super.onPublished(p)
        }

    })
}


// 观察者接口
interface Observer {
    fun update(stock: Int)
}

// 被观察者类
class Product {
    private val observers: MutableList<Observer> = mutableListOf()
    private var stock: Int = 0

    fun addObserver(observer: Observer) {
        observers.add(observer)
    }

    fun removeObserver(observer: Observer) {
        observers.remove(observer)
    }

    fun setStock(stock: Int) {
        this.stock = stock
        notifyObservers()
    }

    private fun notifyObservers() {
        for (observer in observers) {
            observer.update(stock)
        }
    }
}

// 具体观察者类
class User : Observer {
    override fun update(stock: Int) {
        println("User: Stock updated, current stock is $stock")
        // 执行其他操作...
    }
}

// 客户端代码
fun main() {
    val product2 = Product()
    val user1 = User()
    val user2 = User()

    product2.addObserver(user1)
    product2.addObserver(user2)

    product2.setStock(10)
    product2.setStock(5)

    product2.removeObserver(user2)

    product2.setStock(3)
}